package io.gitee.jinceon;

import io.gitee.jinceon.parser.CalculatorBaseVisitor;
import io.gitee.jinceon.parser.CalculatorParser;

import java.math.BigDecimal;
import java.util.Map;

// 实现计算功能的访问器类
public class ExprVisitor extends CalculatorBaseVisitor<BigDecimal> {

    private final Map<String, Number> context;
    public ExprVisitor(Map<String, Number> context) {
        this.context = context;
    }

    @Override
    public BigDecimal visitVariable(CalculatorParser.VariableContext ctx) {
        return new BigDecimal(String.valueOf(context.get(ctx.VAR().getText())));
    }

    // 访问单个整数构成的表达式：Number
    @Override
    public BigDecimal visitNumber(CalculatorParser.NumberContext ctx) {
        return new BigDecimal(ctx.NUMBER().getText());
    }

    // 访问乘除法表达式：expr op=('*'|'/') expr
    @Override
    public BigDecimal visitMulOrDiv(CalculatorParser.MulOrDivContext ctx) {
        BigDecimal left = visit(ctx.expr(0));
        BigDecimal right = visit(ctx.expr(1));
        if (ctx.op.getType() == CalculatorParser.MUL)
            return left.multiply(right);
        return left.divide(right);
    }

    // 访问加减法表达式：expr op=('+'|'-') expr
    @Override
    public BigDecimal visitAddOrSub(CalculatorParser.AddOrSubContext ctx) {
        BigDecimal left = visit(ctx.expr(0));
        BigDecimal right = visit(ctx.expr(1));
        if (ctx.op.getType() == CalculatorParser.ADD)
            return left.add(right);
        return left.subtract(right);
    }

    // 访问表达式加括号：'(' expr ')'
    @Override
    public BigDecimal visitParens(CalculatorParser.ParensContext ctx) {
        return visit(ctx.expr());
    }
}
